package com.dlc.shop.api.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.app.dto.ProdCommDto;
import com.dlc.shop.bean.app.param.ProdCommParam;
import com.dlc.shop.bean.enums.OrderStatus;
import com.dlc.shop.bean.enums.ReturnMoneyStsType;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.model.ProdComm;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.common.util.RedisUtil;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/p/prodComm")
@Tag(name = "商品评论接口")
@AllArgsConstructor
public class ProdCommController {

    private final ProdCommService prodCommService;

    private final OrderItemService orderItemService;

    private final OrderService orderService;

    private final ProductService productService;
    private final ShopDetailService shopDetailService;

    @GetMapping("/prodCommPageByUser")
    @Operation(summary = "根据用户返回评论分页数据" , description = "传入页码")
    public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPage(PageParam page) {
        return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByUserId(page, SecurityUtils.getUser().getUserId()));
    }

    @PostMapping
    @Operation(summary = "添加评论")
    public ServerResponseEntity<Void> saveProdCommPage(@Valid @RequestBody ProdCommParam prodCommParam) {
        Long orderItemId = prodCommParam.getOrderItemId();
        OrderItem orderItem = orderItemService.getOrderItemAndRefundByOrderItemId(orderItemId);
        if (orderItem == null) {
            // 订单项不存在
            throw new YamiShopBindException("yami.address.deleted");
        }
        if (Objects.equals(orderItem.getCommSts(), 1)) {
            // 改订单项已评论，请勿重复评论
            throw new YamiShopBindException("yami.item.has.commented");
        }
        String userId = SecurityUtils.getUser().getUserId();
        String limitKey = "COMM_"+orderItemId;
        Long commonNum = RedisUtil.incr(limitKey, 1);
        if(commonNum==1){
            RedisUtil.expire(limitKey,2);
        }else {
            throw new YamiShopBindException("yami.item.com.repeated");
        }

        Order order = orderService.getOrderByOrderNumberAndUserId(orderItem.getOrderNumber(), userId, true);
        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(orderItem.getReturnMoneySts(), ReturnMoneyStsType.SUCCESS.value())) {
            // 请确认收货后再进行评论
            throw new YamiShopBindException("yami.confirm.receipt");
        }
        Product product = productService.getProductByProdId(orderItem.getProdId());
        if (Objects.isNull(product)) {
            String takeOff = I18nMessage.getMessage("yami.product.no.exist");
            // 商品不存在
            throw new YamiShopBindException(takeOff);
        }
        if (StrUtil.isBlank(prodCommParam.getPics())) {
            prodCommParam.setPics(null);
        }
        prodCommService.comm(orderItem, prodCommParam);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getProdComment")
    @Operation(summary = "根据订单项Id列表获取评论")
    @Parameter(name = "orderItemIds", description = "订单项Id列表" )
    public ServerResponseEntity<List<ProdComm>> getProdComment(@RequestParam("orderItemIds") List<Long> orderItemIds) {
        List<ProdComm> prodCommList = prodCommService.list(new LambdaUpdateWrapper<ProdComm>()
                .in(ProdComm::getOrderItemId, orderItemIds)
                .eq(ProdComm::getUserId, SecurityUtils.getUser().getUserId()));
        if (CollectionUtil.isEmpty(prodCommList)) {
            throw new YamiShopBindException("yami.comment.is.delete");
        }
        return ServerResponseEntity.success(prodCommList);
    }
}
